import 'package:enjoy_plus_hm/pages/home/index.dart';
import 'package:enjoy_plus_hm/pages/mine/index.dart';
import 'package:enjoy_plus_hm/utils/event_bus.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/token.dart';
import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png",
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png",
    },
  ];

  // initState方法上不支持异步
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
      ToastUtil.showInfo(TokenManager().getToken()!);
    });
    eventBus.on<LogoutEvent>().listen((event) {
      // Print the runtime type. Such a set up could be used for logging.
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: [HomePage(), MinePage(currentIndex: currentIndex)],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        items: getBottomNavigationBarItems(),
        onTap: (e) {
          setState(() {
            currentIndex = e;
          });
        },
        type: BottomNavigationBarType.fixed,
        selectedItemColor: Color(0xFF5591af),
        unselectedFontSize: 14,
      ),
    );
  }

  List<BottomNavigationBarItem> getBottomNavigationBarItems() {
    List<BottomNavigationBarItem> listItems = [];
    for (var item in tabBarList) {
      listItems.add(
        BottomNavigationBarItem(
          label: item['title'],
          icon: Image.asset(item['default'], width: 25, height: 25),
          activeIcon: Image.asset(item['active'], width: 25, height: 25),
        ),
      );
    }
    return listItems;
  }
}
